package com.wyw.hemerocallis.service;

import com.wyw.hemerocallis.constant.RoleEnum;
import com.wyw.hemerocallis.entity.HemerocallisPath;
import com.wyw.hemerocallis.entity.HemerocallisRole;
import com.wyw.hemerocallis.entity.HemerocallisRolePath;
import com.wyw.hemerocallis.entity.HemerocallisUserRole;
import com.wyw.hemerocallis.repository.HemerocallisPathRepository;
import com.wyw.hemerocallis.repository.HemerocallisRolePathRepository;
import com.wyw.hemerocallis.repository.HemerocallisRoleRepository;
import com.wyw.hemerocallis.repository.HemerocallisUserRoleRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 权限校验功能服务接口实现
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionService {
    private final HemerocallisPathRepository pathRepository;
    private final HemerocallisRoleRepository roleRepository;
    private final HemerocallisUserRoleRepository userRoleRepository;
    private final HemerocallisRolePathRepository rolePathRepository;

    /**
     * 用户访问接口权限校验
     * @param userId        用户ID
     * @param uri           访问uri
     * @param httpMethod    请求类型
     * @return              true/false
     */
    public Boolean checkPermission(Long userId, String uri, String httpMethod) {
        //查询用户的用户角色对应信息
        HemerocallisUserRole userRole = userRoleRepository
                .findByUserId(userId);

        //如果这个用户找不到记录，直接返回false
        if (null == userRole) {
            log.error("该用户信息在userRole表中不存在:{}", userId);
            return false;
        }

        //如果找不到对应的Role记录，直接返回false
        Optional<HemerocallisRole> role = roleRepository.findById(userRole.getRoleId());
        if(!role.isPresent()) {
            log.error("该角色在Role表中不存在:{}", userRole.getRoleId());
            return false;
        }

        //如果角色是超级管理员，则直接返回true
        if(role.get().getRoleTag().equals(RoleEnum.SUPER_ADMIN.getRoleName())) {
            return true;
        }

        //如果路径没有注册（忽略了，并不是所有接口都需要校验），直接返回true
        HemerocallisPath path = pathRepository.findByPathPatternAndHttpMethod(
                uri, httpMethod);
        if (null == path) {
            return true;
        }

        HemerocallisRolePath rolePath = rolePathRepository
                .findByRoleIdAndPathId(
                        role.get().getId(), path.getId()
                );

        return rolePath != null;


    }


}
